<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <navbar></navbar>
    <!-- 面包屑导航 teamManage -->
    <!-- 添加团队 -->
    <div class="content">
      <h2>礼包管理</h2>
      <h3>数据筛选</h3>
      <div>
        <el-form ref="search" :model="search" :inline="true" id="search" size="small">
          <el-form-item label="礼包编码" prop="code">
            <el-input
              v-model="search.code"
              clearable
              placeholder="请输入礼包编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="礼包名称" prop="name">
            <el-input
              v-model="search.name"
              clearable
              placeholder="请输入礼包名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="礼包支付方式" prop="payType">
            <el-select
              v-model="search.payType"
              placeholder="请选择礼包支付方式"
              clearable
            >
              <el-option
                v-for="(item, index) in dictionaries.gift_package_pay_type"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
                :disabled="index !== 0"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="平台" prop="platformId">
            <el-select
              v-model="search.platformId"
              placeholder="请选择平台"
              clearable
            >
              <el-option
                v-for="item in platformListFilter"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="search.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in dictionaries.enable_status"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData('search', true)">查询</el-button>
            <el-button
              type="primary"
              plain
              @click="fetchData('reset')"
              >重置</el-button
            ></el-form-item
          >
        </el-form>
      </div>
    </div>
    <div class="content">
      <h3 class="data-list-title">数据列表
        <p>
          <span>个人复购佣金：{{ commissionNum }}%</span>
          <el-link type="primary" @click="setCommission">设置</el-link>
        <el-button
          v-if="parArray.indexOf('addPlatform') != -1"
          size="small"
          type="primary"
          @click="showDialog('新增', 'add')"
      >新增</el-button>
        </p>
      </h3>
      <matrix-table v-loading="manage.loading" :dataList="manage.page.list" :config="manage.config" :sortObj="manage.page.sortObj" :platformListObj="platformListFilter" @receiveData="showDetailData"></matrix-table>
      <el-pagination
          v-if="manage.page.list.length > 0"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          :current-page="manage.page.pageNo"
          :page-sizes="[3, 5, 10, 20, 50]"
          :page-size="manage.page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="manage.page.totalNum">
      </el-pagination>
    </div>
    <!--========================== el-dialog =================================-->
    <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :width="dialog.width"
        :append-to-body="true"
        :close-on-click-modal="false"
    >
      <!--
      <template slot="title" v-if="dialog.subTitle">
        <h2 class="dialog-slot-title">{{dialog.title}}</h2>
      </template>
      -->
<!--      <h2 class="dialog-slot-title">{{dialog.title}}</h2>-->
      <template v-if="dialog.type === 'commission'">
        <div class="set-commission">
          <span>个人复购比例</span>
          <el-input v-model="commissionNum" @input="commissionNum = checkValue(commissionNum,2)" class="commission-num"></el-input>%
        </div>
        <div class="dialog-commission">
          <el-button @click="commissionCancel">取 消</el-button>
          <el-button type="primary" @click="commissionSubmit">确 定</el-button>
        </div>
      </template>
      <template v-else>
        <gift-form ref="giftForm" :typeStr="dialog.type" @dialogFromData="handleFromData"></gift-form>
      </template>
    </el-dialog>
    <!--=========================== el-dialog end================================-->

  </div>
</template>

<script>
import navbar from '@/components/navbar.vue'
import MatrixTable from './components/MatrixTable.vue'
import GiftForm from './components/GiftForm.vue'
import common from './mixins/common'
export default {
  mixins: [common],
  name: 'manage',
  components: { navbar, MatrixTable, GiftForm },
  data () {
    return {
      commissionNum: 0,
      search: {
        code: '', // 礼包编码
        name: '', // 礼包名称
        payType: '', // 礼包支付方式
        platformId: '', // 平台
        status: '' // 状态
      },
      giftForm: {
        name: '', // 平台名称 string
        code: '', // 平台编码 string
        type: '', // 类型 string
        sort: '', // 序号 int
        status: '1' // 状态 string
      },
      manage: {
        loading: false,
        page: { list: [], pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 },
        sortObj: { prop: 'marketPrice', order: 'descending' }, // 排序
        config: [
          { prop: 'code', label: '礼包编码', width: 100 },
          { prop: 'name', label: '礼包名称', width: 120, slot: 'giftName' },
          { prop: 'shortName', label: '礼包简称', width: 120 },
          { prop: 'goodsNames', label: '商品', width: 240, slot: 'goodsNames' },
          { prop: 'firstImage', label: '轮播图', slot: 'firstImage' },
          { prop: 'detailImage', label: '详情', slot: 'detailImage' },
          { prop: 'stock', label: '库存'},
          { prop: 'price', label: '价格' },
          { prop: 'points', label: '赠送积分' },
          { prop: 'firstCommissionProportion', label: '佣金', width: 150, slot: 'proportion' },
          { prop: 'payTypeLabel', label: '礼包支付方式', width: 180 },
          { prop: 'platformName', label: '平台', width: 200, slot: 'platformName' },
          { prop: 'statusLabel', label: '状态' },
          { prop: 'validityStartTime', label: '有效期', width: 160, slot: 'validityTime' },
          { prop: 'createdTime', label: '创建时间', width: 160},
          { prop: 'operate', label: '操作', slot: 'button', fixed: 'right', width: 150, align: 'center' }
        ]
      },
      dialog: { visible: false, title: '编辑', width: '640px', type: '', row: {}, batch: false },
      parArray: [] // 按钮权限
    }
  },
  created () {
    this.fetchData()
    this.getButtonTreeDto() // 获取权限设定
    this.getCommission() // 个人复购佣金 提现设置数据查询接口
  },
  /*
  watch: {
    permissionFilterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  */
  methods: {
    fetchData (type, changeCurrentPage) {
      this.manage.loading = true
      if (changeCurrentPage) {
        this.manage.page.pageNo = 1
        this.manage.page.pageSize = 10
        this.manage.page.currentPage = 1
      }
      if (type === 'reset') {
        this.$refs['search'].resetFields()
        this.manage.page.pageNo = 1
        this.manage.page.pageSize = 10
        this.manage.page.currentPage = 1
      }
      let params = {
        pageNo: this.manage.page.pageNo,
        pageSize: this.manage.page.pageSize
      }
      if (type === 'search') {
        params = Object.assign(params, this.search)
        // 去除字符串 前后 空格
        for (const item in params) {
          if (typeof params[item] === 'string') {
            params[item] = params[item].trim()
            if (params[item] === '') { delete params[item] }
          }
        }
      }

      // 修改状态值（1-启用，0-禁用）'
      // if (params.status){ params.status === '1' ? params.status = 1 : params.status = 0 }
      this.$api.matrixPageList(params).then((res) => {
        this.manage.loading = false
        if (res.code === 0) {
          res.data.list.forEach(it => {
            it.goodsNames = it.goodsNames.split(',')
            it.platformName = it.platformName.split(',')
            it.price = `${it.price}元`

            it['firstImageArr'] = []
            const tempImages = it.images.split(',')
            /*
            tempImages.forEach(item => {
              if (item.indexOf('http') < 0 ) {
                item = this.ImgHttps + item
              }
            })
            */
            for (let i = 0; i < tempImages.length; i++) {
              if (tempImages[i].indexOf('http') < 0 ) {
                tempImages[i] = this.ImgHttps + tempImages[i]
              }
            }
            it.firstImageArr = tempImages

            it['detailImageArr'] = []
            if (it.detailImage.indexOf('http') < 0 ) { it.detailImage = this.ImgHttps + it.detailImage }
            it.detailImageArr.push(it.detailImage)

            if (!it.stock){it.stock = '0'}
          })
          this.manage.page.list = res.data.list
          this.manage.page.totalNum = res.data.totalNum
        }
      }).catch((err) => {
        this.manage.loading = false
        console.log(err)
      })
    },
    onCurrentChange (currentChange) {
      this.manage.page.pageNo = currentChange
      this.fetchData('search')
    },
    onSizeChange (sizeChange) {
      this.manage.page.pageNo = 1
      this.manage.page.currentPage = 1
      this.manage.page.pageSize = sizeChange
      this.fetchData('search')
    },
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'GiftManage1'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
      console.log('权限', this.parArray)
    },

    async showDialog (row, type) {
      const t = new Date().getTime()
      // this.$refs.giftForm.resetForm('ruleForm')
      await this.$nextTick();
      this.$nextTick(_ => {
        console.log(typeof this.$refs, this.$refs)
      })
      let title
      switch (type) {
        case 'add':
          title = `新增礼包`
          this.$router.push({query: {type: 'add', t}})
          break
        case 'edit':
          title = `编辑${row.name}`
          // this.$router.push({query: {...this.$route.query, gid: row.id, t}})
          this.$router.push({query: {type: 'edit', gid: row.id, t}})
          break
        default:
          this.$router.push({query: {type: 'details', gid: row.id, t}})
          title = `${row.name}`
      }
      const dialog = {
        visible: true,
        title, type, row,
        width: '650px',
        batch: false,
        subTitle: '(时间：2022年6月)'
      }
      this.dialog = dialog
      console.log('showDetail 查看', this.dialog)
    },
    showDetailData (data) {
      this.showDialog(data.row, data.type)
      // console.log(data)
    },
    handleFromData (data) {
      console.log(data)
      if (data.isClose) {this.dialog.visibl = !data.isClose }
      this.dialog.visible = data.data.visible
      if (data.data.isGetData){ this.fetchData('reset')}
    },
    // 个人复购佣金 提现设置数据查询接口
    getCommission() {
      
      const params = {}
      this.$api.matrixGetPersonelRepurchase(params).then((res) => {
        if (res.code === 0) {
          this.commissionNum = res.data
          console.log(this.commissionNum,'commissionNumcommissionNumcommissionNumcommissionNumcommissionNum')
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 个人复购佣金 设置
    setCommission() {
      const dialog = {
        visible: true,
        title: '个人复购佣金设置',
        type: 'commission',
        width: '450px',
        batch: false,
        subTitle: '(时间：2022年9月)'
      }
      this.dialog = dialog
      console.log('showDetail 查看', this.dialog)
    },
    commissionCancel () {
      // this.commissionNum = 0
      this.getCommission()
      this.dialog.visible = false
    },
    commissionSubmit () {
      const commissionNum = this.commissionNum
      if (commissionNum > 100 ){
        this.$message.warning('输入比例不能超过100% ！')
        return console.log('输入数字太大！')
      }
      this.dialog.visible = false
      const params = {personelRepurchaseRate: this.commissionNum}
      this.$api.matrixSetPersonelRepurchase(params).then((res) => {
        if (res.code === 0) {
          console.log(res)
          this.$message.success('设置成功')
          this.getCommission()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    checkValue (val, limit = 0) {
      val = val.replace(/[^\d.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },

    // 表单验证
    submitForm (formName) {
      const type = this.dialog.type
      this.$refs[formName].validate((valid) => {
        if (valid) {
          switch (type) {
            case 'add':
              this.addPlatform()
              break
            case 'edit':
              this.editPlatform()
              break
            default:
              console.log(type)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import './assets/common';
.content {
  .el-button {
    margin-bottom: 10px;
  }
  .el-badge {
    margin-left: 10px;
  }
}
.roleList {
  border: 1px solid #f0f3fd;
  border-radius: 5px;
  .title {
    color: #333333;
    line-height: 40px;
    padding: 0 10px;
    background-color: #f0f3fd;
    .el-badge {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
  .list {
    padding: 20px;
    .el-tag {
      border: 0;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
.el-dialog{
  background-color: #2D7EDF;
  .el-dialog__body{
    padding: 10px;
    .dialog-content {
      // min-height: 210px;
      .el-tree {
        max-height: 300px;
        overflow: auto;
      }
    }
  }
}
.el-pagination{
  margin: 10px auto;
  text-align: center;
}
</style>
<style lang="scss">
.content {
  .el-link {
    margin: 0 5px;
  }
  h4 {
    padding-top: 10px;
    border-top: 1px solid #bbbbbb;
  }
}
#search{

}
.data-list-title{
  p{
    width: 333px;
    display: inline-block;
    float: right;
    span, a{
      font-size: 14px;
    }
    a{
      padding-left: 10px;
    }
    .el-button{
      margin-left: 20px;
      float: right;
    }
  }

}
.set-commission{
  text-align: center;
  .commission-num{
    margin: 0 10px;
    width: 120px;
  }
}
.dialog-commission{
  margin: 20px auto;
  text-align: center;
  button{
    margin: 0 20px;
  }
}
</style>
